import Vue from 'vue'
import VueRouter from 'vue-router'
import { getToken } from '@/utils/storage.js'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: () => import('@/views/layout.vue'),
    redirect: '/article',
    children: [
      {
        path: 'article',
        component: () => import('@/views/article.vue')
      },
      {
        path: 'collect',
        component: () => import('@/views/collect.vue')
      },
      {
        path: 'like',
        component: () => import('@/views/like.vue')
      },
      {
        path: 'user',
        component: () => import('@/views/user.vue')
      }
    ]
  },
  {
    path: '/login',
    component: () => import('@/views/login.vue')
  },
  {
    path: '/register',
    component: () => import('@/views/register.vue')
  },
  {
    path: '/detail/:id',
    component: () => import('@/views/detail.vue')
  }
]

const router = new VueRouter({
  routes
})

const whitelist = ['/login', '/register']
router.beforeEach((to, from, next) => {
  const token = getToken()
  if (whitelist.includes(to.path)) next()
  else if (token) next()
  else next('/login')
})
export default router
